﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using XCommunity.Data;
using XCommunity.Frames;
using System.Collections.Specialized;
using Ivony.Web;
using XCommunity.Documents;
using XCommunity.Forums.Views;

public partial class Presenter_DocumentsPagingControl : System.Web.UI.UserControl
{

  private int _pageIndex = 1;
  private int _maxPage;


  protected void Page_Init( object sender, EventArgs e )
  {
    if ( !int.TryParse( Request.QueryString["page"], out _pageIndex ) )
    {
      _pageIndex = 1;
    }

    _maxPage = PagingData.GetMaxPage();

    if ( _maxPage == 0 )
      _maxPage = 1;

    if ( _pageIndex > _maxPage )
      _pageIndex = _maxPage;

    if ( _pageIndex < 1 )
      _pageIndex = 1;

  }

  protected void Page_Load( object sender, EventArgs e )
  {

    if ( _maxPage > 1 )
      RenderPageLinks();
  }

  private void RenderPageLinks()
  {

    PagingContainer.Controls.Add( CreatePageButtonLink( 1 ) );

    int minVisiblePage = PageIndex - 3;
    if ( minVisiblePage <= 1 )
      minVisiblePage = 2;

    int maxVisiblePage = PageIndex + 3;
    if ( maxVisiblePage >= _maxPage )
      maxVisiblePage = _maxPage;

    if ( minVisiblePage > 2 )
      PagingContainer.Controls.Add( new LiteralControl( "..." ) );


    for ( int i = minVisiblePage; i <= maxVisiblePage; i++ )
    {
      PagingContainer.Controls.Add( CreatePageButtonLink( i ) );
    }

    if ( maxVisiblePage < _maxPage )
    {
      if ( maxVisiblePage < _maxPage - 1 )
        PagingContainer.Controls.Add( new LiteralControl( "..." ) );

      PagingContainer.Controls.Add( CreatePageButtonLink( _maxPage ) );
    }

  }


  private HyperLink CreatePageButtonLink( int pageIndex )
  {
    HyperLink link = new HyperLink();
    link.CssClass = "PagingLink";
    link.Text = pageIndex.ToString();
    link.NavigateUrl = GetPageUrl( pageIndex );

    return link;
  }

  public string GetPageUrl( int pageIndex )
  {

    NameValueCollection collection = new NameValueCollection( Page.Request.QueryString );
    collection["page"] = pageIndex.ToString();
    UriBuilder builder = new UriBuilder( Page.Request.Url );
    builder.Query = WebUtility.GenerateQueryString( collection );

    return builder.Uri.GetComponents( UriComponents.PathAndQuery, UriFormat.UriEscaped );
  }


  public IPagingData<PostFrameView> PagingData
  {
    get;
    set;
  }

  public int PageIndex
  {
    get { return _pageIndex; }
  }




}
